/**
 * Created by jocky on 2017/6/21.
 */
$().ready(function () {
    $(document).on('click', '.collapse-link', function () {
        var $BOX_PANEL = $(this).closest('.x_panel'),
            $ICON = $(this).find('i'),
            $BOX_CONTENT = $BOX_PANEL.find('.hide-or-show');

        // fix for some div with hardcoded fix class
        if ($BOX_PANEL.attr('style')) {
            $BOX_CONTENT.slideToggle(200, function () {
                $BOX_PANEL.removeAttr('style');
            });
        } else {
            $BOX_CONTENT.slideToggle(200);
            $BOX_PANEL.css('height', 'auto');
        }

        $ICON.toggleClass('fa-chevron-up fa-chevron-down');
    });

    //获取左侧菜单
    getSideMenus();

    //激活弹出框
    var requestUrl = '';
    var hash = window.location.hash;
    if (hash) {
        requestUrl = hash.substr(1);
    }
    if (requestUrl != '/account/activation' && $('#login_flag').val() == 0) {
        swal({
            title: '未激活',
            text: "账户未激活状态下，代理不能发展业务",
            type: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: '去激活',
            cancelButtonText: '先了解系统，稍后去激活'
        }).then(function () {
            //先打开一级菜单
            if (!$("#menu_3").hasClass('active')) {
                $("#menu_3").find('a:first').trigger('click');
            }

            //再打开二级子菜单
            $("#menu_15").find('a').trigger('click');

        }, function (dismiss) {

        });
    }

});

//菜单详情
var menu_detail = {};

/**
 * 动态获取左侧菜单内容
 */
function getSideMenus() {
    //当前激活的菜单项
    var active_menu = {};
    $.getJSON("/interface/side-menus", function (data) {
        //刷新浏览器器，请求路径不为默认值时需要载入当前页面
        var requestUrl = '';
        var hash = window.location.hash;
        if (hash) {
            requestUrl = $.trim(hash.substr(1));
        }

        var str = "";
        //如果没有默认的菜单，或者此菜单的权限被主账户回收，则默认显示第一栏的第一项
        $.each(data, function (i, menu) {
            if (menu.type == 1) {
                str += "<li id='menu_" + menu.id + "'>" +
                    "<a class='first_menu' href='javascript:void(0)' data-href='" + (menu.childNum == 0 ? menu.route : 'none') + "'>" +
                    "<i class='fa " + menu.icon + "'></i>"
                    + menu.name;
                if (menu.childNum != 0) {
                    str += "<span class='fa fa-chevron-down'></span>"
                } else {
                    menu_detail['menu_' + menu.id] = {
                        title: menu.name,
                        loadContent: true,//是否需要发送一次请求.当模块内容已经载入后,不需要再发送请求了
                        requestUrl: menu.route//第一次请求时的url
                    };

                    if ((requestUrl == '' && menu.selected == 1) || requestUrl == $.trim(menu.route)) {
                        active_menu.pid = menu.id;
                        active_menu.id = menu.id;

                    }
                }
                str += "</a>";
            } else {
                str += "<li id='menu_" + menu.id + "'>" +
                    "<a href='javascript:void(0)' data-href='onclick' onclick='" + menu.onclick + "'>" +
                    "<i class='fa " + menu.icon + "'></i>"
                    + menu.name +
                    "</a>";
            }

            if (menu.childNum == 0) return true;

            str += "<ul class='nav child_menu'>";
            $.each(menu.child, function (j, v) {
                if (requestUrl == '' && v.selected == 1) {
                    active_menu.pid = v.pid;
                    active_menu.id = v.id;
                }

                var url = v.route;
                if (v.params != '') {
                    url += "?" + v.params;
                }
                str += "<li id='menu_" + v.id + "'>" +
                    "<a href='javascript:void(0)' data-href='" + url + "'>" + v.name + "</a>" +
                    "</li>";

                menu_detail['menu_' + v.id] = {
                    title: v.name,
                    loadContent: true,//是否需要发送一次请求.当模块内容已经载入后,不需要再发送请求了
                    requestUrl: url//第一次请求时的url
                };

                if ($.trim(requestUrl) == $.trim(url)) {
                    active_menu.pid = v.pid;
                    active_menu.id = v.id;
                }
            });
            str += "</ul>";

        });

        $("#side-menu").html(str);

        if (active_menu.pid != active_menu.id) {
            $("#menu_" + active_menu.id).addClass('current-page');
        }
        $("#menu_" + active_menu.pid).addClass('active').find('ul').show();


        $("#menu_" + active_menu.id + '_div').show();
        //初台化左侧菜单
        init_menu();
        //获取内容
        get_content('menu_' + active_menu.id);
    });
}

/**
 * 获取内容
 *
 * @param menuID
 * @returns {boolean}
 */
function get_content(menuID) {
    if (!menu_detail[menuID]['loadContent']) return false;

    //将当前菜单项强制获取内容改为false
    menu_detail[menuID]['loadContent'] = false;

    $.get(menu_detail[menuID]['requestUrl'], {}, function (content) {
        $('#' + menuID + '_div').html(content);
    });
}

/**
 * 刷新模块内容时，显示loading信息
 *
 * @param menuID
 */
function show_loading(menuID) {
    var loading = "" +
        "<div class='text-center' style='height: 100%'>" +
        "<img style='margin: 150px 0;' src='/images/loading.gif'/>" +
        "</div>";

    $('#' + menuID + '_div').html(loading);
}

/**
 * 翻页获取内容时，显示loading信息
 *
 * @param tableID
 * @param columns
 */
function show_loading_table(tableID, columns) {
    var loading = "" +
        "<tr>" +
        "<td colspan='" + columns + "' class='text-center'>" +
        "<img style='margin: 10px;width: 40px;height: 40px;' src='/images/loading.gif'/>" +
        "</td>" +
        "</tr>";

    $('#' + tableID + '>tbody').html(loading);
}

/**
 *
 * @param domCurrent 当前页DOM
 * @param domTotal  总页数DOM
 * @param type 1:首尾页,2:翻页,3:跳页
 * @param direction type=1时该参数表示首页或尾页,type=2时该参数表示上一页或下一页
 * @returns {*}
 */
function getPageNo(domCurrent, domTotal, type, direction) {
    var pageNo;
    var current_pageNo = parseInt($("#" + domCurrent).val());
    if (!current_pageNo) current_pageNo = 1;
    var current_pageTotal = parseInt($.trim($("#" + domTotal).html()));
    if (!current_pageTotal) current_pageTotal = 1;

    if (type == 1) {
        if (direction == 1) {
            pageNo = 1;
        } else {
            pageNo = current_pageTotal;
        }
    } else if (type == 2) {
        if (direction == 1) {
            pageNo = current_pageNo - 1;
            if (pageNo < 1) pageNo = 1;
        } else {
            pageNo = current_pageNo + 1;
            if (pageNo > current_pageTotal) pageNo = current_pageTotal;
        }
    } else {
        pageNo = current_pageNo;
    }

    return pageNo;
}


/**
 * 将时间戳类型转为字符串类型
 * @param unix_timestamp
 * @param type 1显示全部，2显示年月日
 */
function convertDate(unix_timestamp, type) {
    if (unix_timestamp == 0) return '/';

    var str = "";
    var date = new Date();
    date.setTime(unix_timestamp * 1000);
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    if (month < 10) month = "0" + month;
    var day = date.getDate();
    if (day < 10) day = "0" + day;

    str += year + "-" + month + "-" + day;

    if (type == 1) {
        var hour = date.getHours();
        if (hour < 10) hour = "0" + hour;
        var min = date.getMinutes();
        if (min < 10) min = "0" + min;
        var sec = date.getSeconds();
        if (sec < 10) sec = "0" + sec;

        str += " " + hour + ":" + min + ":" + sec;
    }

    return str;
}

/**
 * 分配模板
 *
 * @param type 1代理，2客户
 * @param uid
 */
function template_assign(type, uid) {
    $.get('/account/assign-template-form', {type: type, uid: uid}, function (html) {
        $('#modal_pop2_title').html('分配模板');
        $('#modal_pop2_body').html(html);
        $('#modal_pop2').modal('show');
    });
}

/**
 * 安全退出
 */
function logout() {
    swal({
        title: '确定退出系统吗?',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
    }).then(function () {
        $.getJSON('/logout', {isRender: 2}, function (json) {
            if (json.code == 1) {
                window.location.href = json.loginUrl;
            }
        })
    }, function (dismiss) {

    });
}

/**
 * 推荐二维码
 *
 * @param url
 */
function showQRCode(url) {
    var host = window.location.host;
    new QRCode(document.getElementById("QRCode"), {
        text: url,
        width: 180,
        height: 180,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
    });
    $("#QRCode img").addClass("img-responsive");
    $("#QRCode img").css("margin", "0 auto");
}